package com.buss.controller;

import com.baomidou.kisso.web.waf.request.WafRequestWrapper;
import com.buss.model.UploadFileLine;
import com.buss.service.UploadFileLineService;
import com.buss.service.UploadFileTypeService;
import com.buss.storage.FileSystemStorageService;
import com.buss.storage.StorageProperties;
import com.buss.util.CommonUtil;
import com.buss.util.OSProperties;
import com.buss.util.RandomUtil;
import com.buss.util.map.Result;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * controller基类
 *
 */
public abstract class BaseFileController {

	public static final Logger LOG = Logger.getLogger(BaseFileController.class);

	@Value("${location}")
	public String location;
	public String repo = OSProperties.getUrlRepo();

	@Value("${max-file-size-limit}")
	public String maxFileSizeLimit;

	@Autowired
	public UploadFileLineService service;
	@Autowired
	public UploadFileTypeService uploadFileTypeService;

	/**
	 * 公共上传方法
	 * @param file
	 */
	public String upload(MultipartFile file, String path){
		String filePath = location + path;
//		log.debug(filePath);
		StorageProperties storageProperties = new StorageProperties();
		storageProperties.setLocation(filePath);
		FileSystemStorageService fileSystemStorageService = new FileSystemStorageService(storageProperties);
		fileSystemStorageService.store(file); //上传
		return filePath + file.getOriginalFilename();
	}

	/**
	 * 记日志
	 * @param logFormat
	 * @param args
	 */
	public void logFormat(String logFormat, Object[] args)
	{
		LOG.info(String.format(logFormat, args));
	}

	/**
	 * 保存数据库
	 * @param uploadFileLine
	 */
	public void saveLine (UploadFileLine uploadFileLine) {
		//先查文件流水表，判断上传的文件是否存储过
		UploadFileLine uploadFileLineForm = new UploadFileLine();
		uploadFileLineForm.setFilePath(uploadFileLine.getFilePath()); //查询条件：文件存放路径
		List<UploadFileLine> listUploadFileLine = service.select(uploadFileLineForm);
		if(listUploadFileLine!=null && listUploadFileLine.size()>0){
			//存在，则修改
			uploadFileLine.setId(listUploadFileLine.get(0).getId()); //设置ID
			service.updateByPrimaryKey(uploadFileLine); //更新
		}else {
			//不存在，新增
			//插入数据库
			service.insert(uploadFileLine);
		}
	}

	/**
	 * 文件上传，支持多文件
	 */
	public Map<String, Object> handleFileUploadSimple (HttpServletRequest request, String RTN) {
		Map<String, Object> response = new HashMap<String,Object>();
		/**
		 * 过滤 XSS SQL 注入
		 */
		WafRequestWrapper wr = new WafRequestWrapper(request);
		String MODULECODE = wr.getParameter("MODULECODE");     // 模块编码
		String FILETYPECODE = wr.getParameter("FILETYPECODE"); // 文件类型编码
		/*------------------------------- 参数检验 开始 -------------------------------*/

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		List<Map<String, Object>> listMap = new ArrayList<>();
		MultipartFile file = null;

		//循环获取文件流，执行上传，并记录上传流水
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			file = entity.getValue();// 获取上传文件对象
			if(file.isEmpty()){
				response.put(RTN, new Result().addErrorMsg("No file, Not upload!"));
				return response;
			}
			String filename = file.getOriginalFilename();
			String fjidback = RandomUtil.get32UUID();
			LOG.info("{ [附件详情] - [名称=" +filename
					+"] [类型="+file.getContentType()
					+"] [大小="+file.getSize()+"字节(b)"
					+"] [ID="+fjidback
					+"] }");

			//文件大小限制
			if(file.getSize()> Long.parseLong(maxFileSizeLimit)){
				response.put(RTN, new Result().addErrorMsg("上传失败：文件大小不能超过2M!"));
				return response;
			}

			//拼接文件存放路径
			String sufPath = "";
			if (!StringUtils.isBlank(MODULECODE) && !StringUtils.isBlank(FILETYPECODE)) {
				sufPath = MODULECODE+ "/" +FILETYPECODE+ "/";
			}else
			if (!StringUtils.isBlank(MODULECODE)) {
				sufPath = MODULECODE+ "/" ;
			}else
			if (!StringUtils.isBlank(FILETYPECODE)) {
				sufPath = FILETYPECODE+ "/";
			}else
			{	//按时间分类
//				sufPath = "Unknown"+ "/";
//				sufPath = "undefined"+ "/";
				sufPath = CommonUtil.getStdfDate2()+ "/";
			}

			String filePath = upload(file , sufPath); //文件存放路径
			String fileWebUrl = repo + sufPath +filename; //文件访问URL
			String fileWebUrlEncode = fileWebUrl;
			fileWebUrlEncode = fileWebUrlEncode.replaceAll(" ","%20"); //%20就代表空格的编码

			UploadFileLine uploadFileLine = new UploadFileLine();
			uploadFileLine.setFilePath(filePath);
			uploadFileLine.setFileType(file.getContentType());
			uploadFileLine.setFileWebUrl(fileWebUrlEncode);
			uploadFileLine.setCrtDatetime(CommonUtil.getStdfDateTime());
			uploadFileLine.setCrtBy("");
			uploadFileLine.setFjidback(fjidback); //附件ID 本地上传后返回,修改时必传,uuid
			saveLine(uploadFileLine);


			//封装返回内容
			Map<String, Object> datalist = new HashMap<String,Object>();
			datalist.put("FJIDBACK", fjidback);
			datalist.put("PATH", fileWebUrlEncode);
			listMap.add(datalist);
		}
		response.put(RTN, new Result().success());
		response.put("datalist", listMap);
		return response;
	}



}
